<?php

/**
 * 微信类
 */
namespace app\admin\controller;

use app\common\controller\HomeCommon;
use app\common\model\Label;
use think\Cache;
use think\Config;
use think\Controller;
use think\Db;
use think\Request;
use think\View;

class Wx extends Controller
{
    public function test(){
        $template=array(
                'first'=>array('value'=>"您的活动已通过",'color'=>"#FF0000"),
               'delivername'=>array('value'=>"您的活动已通过",'color'=>"#FF0000"),
            'ordername'=>array('value'=>"您的活动已通过",'color'=>"#FF0000"),
                'remark' =>array('value'=>'备注：这是测试','color'=>'#FF0000'),
            );
        $res=$this->sendTplNotice('ol4m81dqlTNF7sVgjtCP8VLcE1Rw',' _Ee7BimX1bhuI5IkOEhb_YMQQEU_xZmrw3YvlP0KkbM',$template,'');
        dd($res);
    }
    /***获取7200秒的access_token**/
    public function get_access_token()
    {
        $wx=Db::connect(Config::get('db_cq'))->table('cq_wx_info')->find();
        if ($wx['expire_time']>time()){
            return $wx['access_token'];
        }
        $url = "https://api.weixin.qq.com/cgi-bin/token";
        $params=[
            'grant_type'=>'client_credential',
            'secret'=>trim($wx['sercet']),
            'appid'=>trim($wx['appid']),
        ];
        $res=httpRequest($url,'GET',$params);
        $exp=bcadd(time(),7200,0);
        Db::connect(Config::get('db_cq'))->table('cq_wx_info')->where('id',$wx['id'])->update(['expire_time'=>$exp,'access_token'=>$res['access_token']]);
        return $res['access_token'];
    }

    public function sendTplNotice($touser, $template_id, $postdata, $url = '', $topcolor = '#FF683F') {

        if(empty($touser)) {

            return error(-1, '111参数错误,粉丝openid不能为空');

        }

        if(empty($template_id)) {

            return error(-1, '2222参数错误,模板标示不能为空');

        }

        if(empty($postdata) || !is_array($postdata)) {

            return error(-1, '333参数错误,请根据模板规则完善消息内容');

        }

        $token = $this->get_access_token();





        $data = array();

        $data['touser'] = $touser;

        $data['template_id'] = trim($template_id);

        $data['url'] = trim($url);

        $data['topcolor'] = trim($topcolor);

        $data['data'] = $postdata;


//        $data = json_encode($data);
        $post_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$token;
        $response=sendtest($post_url,$data);
        $response=json_decode($response,true);
        if($response['errcode']!=0) {

            return error(-1, "访问公众平台接口失败, 错误: {$response['message']}");

        }
        return true;

    }
}
